var params = app.getRequestParams();
var backEditFlag = true;
$(function(){

    $('#fixtable_zu').fixgrid({
        noscroll:true,
        width:800,
        columns:[
            [
                {field:'serialnumber',title:'',width:30},
                {field:'o',title:'<span id="zhj">组合件</span>',width:60,formatter:function () {
                        return gridOpt('#fixtable_zu');
                    }},
                {
                    field:'productId',
                    title:'<span class="red">*</span>商品 -- 扫描枪录入<span init="off" style="position: relative;cursor: pointer;" id="productTitleIcon"></span>',
                    width:200,
                    editor:'search',
                    searchData:function(that){
                        return $(that).parent().data().product;
                    },
                    click:function(searchId){
                        datagridSearchClick(searchId,'#fixtable_zu');
                    },
                    url:'../../common/product_list.html',
                    editBefore:editBefore
                }
            ],
            [
                {field:'unitId',title:'<span class="red">*</span>单位',width:80,editor:'combobox',editBefore:editBefore,
                    getData:function(cell,callback){
                        var rowData = cell.parent().data().product;
                        app.request({
                            url:'product/getMultiUnit',
                            data:{productId:rowData.id},
                            success:function (resp) {
                                var comboData = [{id:rowData.unitId,name:rowData.unitName}];
                                comboData.merge(resp.data);
                                callback(comboData);
                            }
                        });
                    },comboboxData:function (that) {
                        return $(that).data();
                    }
                },
                {field:'number',title:'<span class="red">*</span>数量',width:80,editor:'decimal',editBefore:editBefore},
                {field:'price',title:'<span class="red">*</span><span id="priceOut">出库成本</span>',width:120,editor:'decimal',editBefore:editBefore}
            ]
        ]
    });
    
    $('#fixtable_ge').fixgrid({
        noscroll:true,width:800,
        columns:[
            [
                {field:'serialnumber',title:'',width:30},
                {field:'o',title:'<span id="zj">子件</span>',width:60,formatter:function () {
                        return gridOpt('#fixtable_ge');
                    }},
                {
                    field:'productId',
                    title:'<span class="red">*</span>商品 -- 扫描枪录入<span init="off" style="position: relative;cursor: pointer;" id="productTitleIcon"></span>',
                    width:200,
                    editor:'search',
                    searchData:function(that){
                        return $(that).parent().data().product;
                    },
                    click:function(searchId){
                        datagridSearchClick(searchId,'#fixtable_ge');
                    },
                    url:'../../common/product_list.html',
                    editBefore:editBefore
                }
            ],
            [
                {field:'unitId',title:'<span class="red">*</span>单位',width:80,editor:'combobox',editBefore:editBefore,
                    getData:function(cell,callback){
                        var rowData = cell.parent().data().product;
                        app.request({
                            url:'product/getMultiUnit',
                            data:{productId:rowData.id},
                            success:function (resp) {
                                var comboData = [{id:rowData.unitId,name:rowData.unitName}];
                                comboData.merge(resp.data);
                                callback(comboData);
                            }
                        });
                    },comboboxData:function (that) {
                        return $(that).data();
                    }
                },
                {field:'number',title:'<span class="red">*</span>数量',width:80,editor:'decimal',editBefore:editBefore},
                {field:'price',title:'<span class="red">*</span><span id="priceOut">入库成本</span>',width:120,editor:'decimal',editBefore:editBefore}
            ]
        ]
    });

    
    
    laydate.render({
        elem: '#order_date',value:app.getServerDate()
    });
    
    $('#storeId').combobox({
        width:240,noDefault:true,
        url:'store/select',
        name:'splitProduct.storeId',
        valueField:'id',
        textField:'name'
    });
    
    initButtons({service:'splitProduct',htmlName:'split',orderText:'拆装',codePrefix:'CZ',orderType:0,gridId:'#fixtable_zu'});
    
    if(params.id){
        app.request({
            url:'splitProduct/getOrder',
            data:{id:params.id},
            success:function (resp) {
                initEdit(resp.data);
                layer.closeAll('loading');
            }
        });
    }else{
        createRow('#fixtable_zu');createRow('#fixtable_zu');createRow('#fixtable_zu');
        createRow('#fixtable_ge');createRow('#fixtable_ge');createRow('#fixtable_ge');
        $('#order_title').html('新增调拨单');
    }
});

function initEdit(order){
    var details = order.details;
    
    init_edit_buttons(order,'#fixtable_zu');
    
    $('#order_title').html('编辑拆装单[ CZ'+order.code+' ]');
    
    $('#order_date').val(app.time2str(parseInt(order.date)));
    $('textarea[name="order.remarks"]').val(order.remarks);
    $('input[name="splitProduct.type"][value="'+order.type+'"]').prop('checked',true);
    
    var index = 0;
    for (var i=0 ; i<details.length ; i++){
        var detail = details[i];
        if(detail.type==1){
            init_edit_detail(detail,index,'#fixtable_zu');    
            index++;
        }
    }
    
    index = 0;
    for (var i=0 ; i<details.length ; i++){
        var detail = details[i];
        if(detail.type==2){
            init_edit_detail(detail,index,'#fixtable_ge');    
            index++;
        }
    }
}

function init_edit_detail(detail,i,gridId) {
    var product = {};
    product.id = detail.productId;
    product.name = detail.productName;
    createRow(gridId);
    var leftRow = $(gridId+' .ctx-left .vui-table .vui-table-row').eq(i);
    var rightRow = $(gridId+' .ctx-right .vui-table .vui-table-row').eq(i);
    var searchCell = leftRow.find('.vui-table-cell[field="productId"]');
    searchCell.data({product:product});
    searchCell.html(product.name);
    leftRow.data({product:product});
    rightRow.data({product:product});
    rightRow.find('.vui-table-cell[field="unitId"]').html(detail.unitName).data({value:detail.unitId,text:detail.unitName});
    rightRow.find('.vui-table-cell[field="number"]').html(app.div(detail.number,100).replace('.00',''));
    rightRow.find('.vui-table-cell[field="price"]').html(app.div(detail.price,100));
    
}

function createRow(id) {
    $(id).fixgrid('loadData',{rows:[{}]});
    refreshRowNumber(id);
}

//商品选择后
function productSelected(cell,gridId){
    var obj = productSelectedCommon(cell,gridId);
    var product = obj.product;
    var rightRow = obj.rightRow;

    rightRow.find('.vui-table-cell[field="unitId"]').html(product.unitName).data({value:product.unitId,text:product.unitName});
    rightRow.find('.vui-table-cell[field="number"]').html(1);

}


//保存
function saveAction(saveType,obj){
    var data = app.serializeForm();
    data['splitProduct.date'] =new Date(data['splitProduct.date']).getTime();
    data.saveType = saveType;

    var index = 0;
    $.each(details_zu,function(i,row){
        for ( var n in row ){
            data["splitProductDetails["+index+"]."+n] = row[n];
        }
        data["splitProductDetails["+index+"].ord"] = i;
        data["splitProductDetails["+index+"].type"] = 1;
        index++;
    });

    $.each(details_ge,function(i,row){
        for ( var n in row ){
            data["splitProductDetails["+index+"]."+n] = row[n];
        }
        data["splitProductDetails["+index+"].ord"] = i;
        data["splitProductDetails["+index+"].type"] = 2;
        index++;
    });

    var url = 'splitProduct/insert';
    if(params.id){
        data['splitProduct.id'] = params.id;
        url = 'splitProduct/update';
    }

    doSave(url,data,saveType,obj);
}

//表单检查
var details_zu = [],details_ge=[],accounts=[];
function checkForm(){
    var checkOptions = [
        {type:'input',name:'splitProduct.date',verify:[{type:'required'}]},
        {type:'input',name:'splitProduct.storeId_text',verify:[{type:'required'}]}
    ];

    if(app.checkForm(checkOptions)){
        details_zu = [],details_ge=[];
        details_zu = getFixedTableData('#fixtable_zu',1);
        if(details_zu.length==0){
            return false;
        }
        details_ge = getFixedTableData('#fixtable_ge',2);
        if(details_zu.length>0 && details_ge.length>0){
            return true;
        }
    }
    return false;
}

function getFixedTableData(tableId,type){
    var title = type==1?"母件":"子件";
    var titleStone = type==1?"出库":"入库";
    var tipFlag = false;
    var details = [];
    
    $(tableId+' .ctx-left .vui-table-row').each(function () {
        var product = getRowEleProduct($(this));
        if( product && product.id ){
            var n = $(this).attr('i');
            //body区域对应行
            var bodyTr = $(tableId+' .ctx-right .vui-table-row').eq(n);
    
            var detail = {productId:product.id};
            // 单位
            var unitNameData = getField(bodyTr,'unitId').data();
            detail.unitId = unitNameData.value;
            detail.unitMain = unitNameData.main ? 1 : 0;
            // 单价
            var price = getField(bodyTr,'price').html();
            if( price == null || price.length == 0 ){
                app.message(layer,title+titleStone+'成本未填写');
                tipFlag = true;
                return false;
            }
            detail.price = app.mul(price,app.DIV,0);
            detail.storeId = $('input[name="splitProduct.storeId"]').val();
            detail.companyId = top.loginCompanyId;
            // 数量
            detail.number = app.mul(getField(bodyTr,'number').html(),app.DIV,0);
            details.push(detail);
        }
    });

    if(details.length > 0 && !tipFlag){
        return details;
    }else{
        if(!tipFlag){
            app.msg(layer,title+'至少填写一条'+title+'记录',2);
        }

    }
    return [];
}